<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img class="preview" v-if="avatar" :src="avatar" alt="" />
      <img class="preview" v-else src="../../../assets/images/avatar.jpg" alt="" />

      <!-- 按钮区域 -->
      <div class="btn-box">
          <input @change="changeHandler" ref="inpImg" type="file" accept="image/*"
          style="display:none">
        <el-button @click="$refs.inpImg.click()" type="primary" icon="el-icon-plus">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="!avatar" @click="upAvatar">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data () {
    return {
      avatar: ''
    }
  },
  methods: {
    changeHandler (e) {
      if (e.target.files.length === 0) return
      const fr = new FileReader()
      fr.readAsDataURL(e.target.files[0])
      fr.onload = e => {
        this.avatar = e.target.result
      }
    },
    async upAvatar () {
      // 将头像上传
      const { data: res } = await this.$http.patch('/my/update/avatar', { avatar: this.avatar })
      if (res.code !== 0) return
      this.$store.dispatch('initUserInfo')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
  width: 350px;
  height: 350px;
}
</style>
